package siwi.map.android;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockActivity;
import com.alibaba.fastjson.JSON;
import com.wmw.Utility.Common;
import com.wmw.Utility.Encryption;
import com.wmw.Utility.MSG;
import com.wmw.Utility.SRConstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Login extends SherlockActivity implements ActionBar.TabListener {
	public static final int _SHOW_GUIDE_OK = 1;
	public static Activity _Activity = null;
	/** Called when the activity is first created. */
	// 1.含有loading效果(多线程处理,实时返回数据)
	// 2.登录不成功能够提示出错原因
	// 3.低电量运行程序,是否会自动杀掉Service进程
	// 4.禁止旋转屏幕
	// 5.多分辨率自适应
	// 6.蓝牙能否在用户不知情况下传递数据
	// 7.签名
	// 8.apk加密
	// 9.绑定手机的唯一标识
	// 10.版权所有
	// 11.登录界面光标在最后,而不是开始
	// 12.开机启动
	// 13.签名不一致
	// 14.版本设置
	// 15.服务端是否有版本号
	private String userName;
	private String password;
	private boolean _rememberUsernameAndPassword = false;

	private EditText _etUsername;
	private EditText _etPassword;
	private Button _btnSubmit;
	private TextView _tvRegister;
	private static final int MENU_EXIT = Menu.FIRST - 1;
	private static final int MENU_ABOUT = Menu.FIRST;
	
	/** 如果登陆失败,这个可以给用户确切的消息显示,true是网络连接失败,false是用户名和密码错误 */
	private boolean isNetError;

	/** 登录loading提示框 */
	private ProgressDialog proDialog;

	/** 登录后台通知更新UI线程,主要用于登录失败,通知UI线程更新界面 */
	Handler loginHandler = new Handler() {
		public void handleMessage(Message msg) {
			isNetError = msg.getData().getBoolean("isNetError");
			if (proDialog != null) {
				proDialog.dismiss();
			}
			if (isNetError) {
				Toast.makeText(Login.this, "登陆失败:\n1.请检查您网络连接.\n2.请联系我们.!",
						Toast.LENGTH_SHORT).show();
			}
			// 用户名和密码错误
			else {
				Toast.makeText(Login.this, "登陆失败,请输入正确的用户名和密码!",
						Toast.LENGTH_SHORT).show();
				// 清除以前的SharePreferences密码
				clearSharePassword();
			}
		}
	};

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// timer.schedule(task, 1000);
		SharedPreferences preferences = getSharedPreferences(
				SRConstant._FirstTimeGuide, MODE_PRIVATE);
		Log.d(Common.GetLineInfo(),
				"" + preferences.getBoolean(SRConstant._FTG_FirstTimeRun, true));
		if (preferences.getBoolean(SRConstant._FTG_FirstTimeRun, true)) {
			Editor editor = preferences.edit();
			editor.putBoolean(SRConstant._FTG_FirstTimeRun, false);
			editor.commit();
			
			Intent intent = new Intent();
			intent.setClass(Login.this, FirstTimeGuide.class);
			startActivityForResult(intent, _SHOW_GUIDE_OK);
		}
		initActionBar();
		setContentView(R.layout.login);
		initViews();
		initData();
		// 需要去submitListener里面设置URL
		setListener();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == _SHOW_GUIDE_OK) {
			Log.d(Common.GetLineInfo(), "-");
		}
	}
	
	private void initActionBar(){
		// Action bar.
		Log.d(Common.GetLineInfo(), "-");
		ActionBar actionBar = getSupportActionBar();
		ActionBar.LayoutParams params = new ActionBar.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
				Gravity.CENTER);
		View view = LayoutInflater.from(this).inflate(
				R.layout.action_bar_empty, null);
		actionBar.setCustomView(view, params);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);

		TextView tv = (TextView)view.findViewById(R.id.ABE_Title);
		tv.setText("登录");
	}
	@Override
	protected void onStart() {
		super.onStart();
		_Activity = this;
	}

	@Override
	protected void onPause() {
		super.onPause();
		_Activity = null;
	}

	private void initData() {
		SharedPreferences share = getSharedPreferences(SRConstant._SR_Login, 0);
		String userName = share.getString(SRConstant._L_Username, "");
		String password = share.getString(SRConstant._L_Password, "");

		try {
			userName = Encryption.decryptAES(Encryption._Seed, userName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Log.i(Common.MARS, "userName -[" + userName + "], password -["
				+ password + "]");

		if (!"".equals(userName) && !"".equals(password))
			_rememberUsernameAndPassword = true;

		if (!"".equals(userName)) {
			_etUsername.setText(userName);
		}

		if (!"".equals(password)) {
			_etPassword.setText("******");
		}

		// 如果密码也保存了,则直接让登陆按钮获取焦点
		if (_etPassword.getText().toString().length() > 0) {
			_btnSubmit.requestFocus();
			_etPassword.requestFocus();
		}
		share = null;
	}

	private void initViews() {
		_etUsername = (EditText) findViewById(R.id.loginUserNameEdit);
		_etPassword = (EditText) findViewById(R.id.loginPasswordEdit);
		_btnSubmit = (Button) findViewById(R.id.loginSubmit);
		_tvRegister = (TextView) findViewById(R.id.register);
	}

	/**
	 * 检查用户登陆,服务器通过DataOutputStream的dos.writeInt(int);来判断是否登录成功(
	 * 服务器返回int>0登陆成功,否则失败),登陆成功后根据isRememberMe来判断是否保留密码(用户名是会保留的),
	 * 如果连接服务器超过5秒,也算连接失败.
	 * 
	 * @param userName
	 *            用户名
	 * @param password
	 *            密码
	 * @param validateUrl
	 *            检查登陆的地址
	 * */
	private boolean validateLocalLogin(String userName, String password,
			String validateUrl) {
		// 用于标记登陆状态
		boolean loginState = false;
		HttpURLConnection conn = null;
		DataInputStream dis = null;
		try {
			URL url = new URL(validateUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			conn.connect();
			dis = new DataInputStream(conn.getInputStream());
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				Log.d(Common.GetLineInfo(),
						"getResponseCode() not HttpURLConnection.HTTP_OK");
				isNetError = true;
				return false;
			}
			// 读取服务器的登录状态码
			int loginStateInt = dis.readInt();
			if (loginStateInt > 0) {
				loginState = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			isNetError = true;
			Log.d(this.toString(), e.getMessage() + "  127 line");
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		// TODO
		loginState = true;
		// 登陆成功
		if (loginState) {
			saveSharePreferences(true, true);
		} else {
			// 如果不是网络错误
			if (!isNetError) {
				clearSharePassword();
			}
		}
		return loginState;
	}

	/**
	 * 如果登录成功过,则将登陆用户名和密码记录在SharePreferences
	 * 
	 * @param saveUserName
	 *            是否将用户名保存到SharePreferences
	 * @param savePassword
	 *            是否将密码保存到SharePreferences
	 * */
	private void saveSharePreferences(boolean saveUserName, boolean savePassword) {
		SharedPreferences share = getSharedPreferences(SRConstant._SR_Login, 0);
		if (saveUserName) {
			String encryped = _etUsername.getText().toString();
			try {
				encryped = Encryption.encryptAES(Encryption._Seed, encryped);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d(Common.MARS, "userName - " + encryped + Common.GetLineInfo());
			share.edit().putString(SRConstant._L_Username, encryped).commit();
		}

		if (savePassword) {
			String encryped = _etPassword.getText().toString();
			try {
				encryped = Encryption.encryptAES(Encryption._Seed, encryped);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d(Common.MARS, "password - " + encryped + Common.GetLineInfo());
			share.edit().putString(SRConstant._L_Password, encryped).commit();
		}

		share = null;
	}

	/** 登录Button Listener */
	private OnClickListener submitListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO
			proDialog = ProgressDialog.show(Login.this, "连接中..",
					"连接中..请稍后....", true, false);
			// 开一个线程进行登录验证,主要是用于失败,成功可以直接通过startAcitivity(Intent)转向
			Thread loginThread = new Thread(new LoginFailureHandler());
			loginThread.start();
		}
	};

	// .start();
	// }
	// };

	/** 注册Listener */
	private OnClickListener registerLstener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			// TODO
			intent.setClass(Login.this, RegisterFirstStep.class);
			// 转向注册页面
			startActivity(intent);
		}
	};

	/** 设置监听器 */
	private void setListener() {
		_btnSubmit.setOnClickListener(submitListener);
		_tvRegister.setOnClickListener(registerLstener);
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// menu.add(0, MENU_EXIT, 0, getResources().getText(R.string.MENU_EXIT));
	// menu.add(0, MENU_ABOUT, 0, getResources().getText(R.string.MENU_ABOUT));
	//
	// return super.onCreateOptionsMenu(menu);
	// }

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) {
		case MENU_EXIT:
			finish();
			break;
		case MENU_ABOUT:
			alertAbout();
			break;
		}
		return true;
	}

	/** 弹出关于对话框 */
	private void alertAbout() {
		new AlertDialog.Builder(Login.this)
				.setTitle(R.string.MENU_ABOUT)
				.setMessage(R.string.aboutInfo)
				.setPositiveButton(R.string.ok_label,
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
							}
						}).show();
	}

	/** 清除密码 */
	private void clearSharePassword() {
		SharedPreferences share = getSharedPreferences(SRConstant._SR_Login, 0);
		share.edit().putString(SRConstant._L_Password, "").commit();
		share = null;
	}

	class LoginFailureHandler implements Runnable {
		@Override
		public void run() {
			userName = _etUsername.getText().toString();
			password = _etPassword.getText().toString();
			Log.d(Common.GetLineInfo(), "user name - " + userName
					+ ", password - " + password);
			// TODO
			// 这里换成你的验证地址
			String validateURL = "http://192.168.1.229:8080/android_server/LoginValidate?userName="
					+ userName + "&password=" + password;
			boolean loginState = validateLocalLogin(userName, password,
					validateURL);

			Log.d(Common.GetLineInfo(), "login state -" + loginState);
			// 登陆成功
			if (loginState) {
				// TODO
				startService(new Intent(Login.this, GPSLocateService.class));
				startService(new Intent(Login.this, OrderFormReceiver.class));
				// 传输需要的数据到登陆后的界面
				// 转向登陆后的页面
				Intent intent = new Intent(Login.this, Home.class);
				intent.putExtra("a", 1);
				startActivity(intent);
				proDialog.dismiss();
			} else {
				// 通过调用handler来通知UI主线程更新UI,
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putBoolean("isNetError", isNetError);
				message.setData(bundle);
				loginHandler.sendMessage(message);
			}
		}

	}


	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

}
